#!/usr/bin/python
#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
from xml.etree.ElementTree import parse
from xml.etree.ElementTree import Element, SubElement, ElementTree, fromstring



class GPXtoKML:
    def ns_tag( self, el ):
        if el.tag[0] == '{':
            return el.tag[1:].split("}")
        else:
            return (None, el.tag)

    def translate( self, gpx_in, kml_out ):
        tree = parse(gpx_in)
        elem = tree.getroot()
        (ns,tag) = self.ns_tag(elem)
        if tag != 'gpx':
            return False
        kml = Element('kml')
        #kml.attrib['creator'] = 'PhotoLocate'
        kml.attrib['xmlns'] = 'http://earth.google.com/kml/2.2'
        doc = SubElement(kml, 'Document')
        SubElement(doc, 'name').text = 'Track-home1'
        folder = SubElement(doc, 'Folder')
        SubElement(folder, 'name').text = 'Tracks'
        placemark = SubElement(folder, 'Placemark')
        SubElement(placemark, 'name').text = 'Track-home1'
        multi = SubElement(placemark, 'MultiGeometry')
        style =  SubElement(placemark, 'Style')
        linestyle = SubElement(style, 'LineStyle')
        SubElement(linestyle, 'color').text = 'FFE600E6'
        SubElement(linestyle, 'width').text = '4'
        SubElement(placemark, 'description').text = '&nbsp;'
        SubElement(folder, 'open').text = '1'
        SubElement(folder, 'visibility').text = '1'
        SubElement(doc, 'Snippet').text = 'hello world'
        SubElement(doc, 'open').text = '1'
        SubElement(doc, 'visibility').text = '1'

        for track in elem:
            for seg in track:
                (ns,tag) = self.ns_tag(seg)
                if tag == 'trkseg':
                    linestr = SubElement(multi, 'LineString')
                    #altmode = SubElement(linestr, 'altitudeMode').text = 'clampedToGround'
                    text = ""
                    for x in seg:
                    #idx = 0
                    #xy_prev = ""
                    #while idx < len(seg):
                        #x = seg[idx]
                        # Thin file by using a bigger increment
                        #idx = idx + 1
                        # The following line commented out because it sometimes
                        # returns None.
                        #elevation = x.findtext('{http://www.topografix.com/GPX/1/0}ele')
                        text += "%s,%s " % (x.attrib["lon"], 
                                            x.attrib["lat"])
                        #xy_text = "%f,%f" % (float(x.attrib["lon"]), 
                        #                         float(x.attrib["lat"]))
                        #if xy_text != xy_prev:
                        #    #text += "%s,%s " % (xy_text, elevation)
                        #    text += "%s " % (xy_text)
                        #    pass
                        #xy_prev = xy_text
                        
                        pass
                    SubElement(linestr, 'coordinates').text = text
                    SubElement(linestr, 'tessellate').text = '0'
                    pass
                pass
            pass
        kml_out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        ElementTree( kml ).write( kml_out )
        return True
    pass
    
def main():
    GPXtoKML().translate(open(sys.argv[1],'r'), open(sys.argv[2],'w'))
    pass

if __name__ == '__main__':
    main()
